import { seedData } from "./seeds";

export const store = {
    state: {
        seedData
    },
    getActiveDay() {
        return this.state.seedData.find((day) => day.active);
    },
    setActiveDay(dayId) {
        this.state.seedData.map((dayObj) => {
            dayObj.id === dayId ? dayObj.active = true : dayObj.active = false
        })
    },
    submitEvent(eventDetails) {
        //得到当前日
        const activeDay = this.getActiveDay();
        //追加event
        activeDay.events.push({ "details": eventDetails, "edit": false });
    },
    //找到要编辑的event
    editEvent(dayId, eventDetails) {
        //所有的先设为非编辑
        this.resetEditOfAllEvents();

        /*
        //找到day
        const dayObj = this.state.seedData.find(
            day => day.id === dayId
        );
        //找到event
        const eventObj = dayObj.events.find(
            event => event.details === eventDetails
        );
        */
        //将上面的查找 转为函数 简化程序
        const eventObj = this.getEventObj(dayId, eventDetails)

        //设置成编辑状态
        eventObj.edit = true;
    },
    //所有的event改为false
    resetEditOfAllEvents() {
        this.state.seedData.map((dayObj) => {
            dayObj.events.map((event) => {
                event.edit = false;
            });
        });
    },
    updateEvent(dayId, originalEventDetails, newEventDetails) {
        /*
        //找到day
        const dayObj = this.state.seedData.find(
            day => day.id === dayId
        );
        //找到event
        const eventObj = dayObj.events.find(
            event => event.details === originalEventDetails
        );
        */
        //将上面的查找 转为函数 简化程序
        const eventObj = this.getEventObj(dayId, originalEventDetails)

        //更新并修改编辑状态
        eventObj.details = newEventDetails;
        eventObj.edit = false;
    },
    //根据dayId和eventDetails找到event
    getEventObj(dayId, eventDetails) {
        //找到day
        const dayObj = this.state.seedData.find(
            day => day.id === dayId
        );
        //找到event
        const eventObj = dayObj.events.find(
            event => event.details === eventDetails
        );
        return eventObj;
    },
    deleteEvent(dayId, eventDetails) {

        const dayObj = this.state.seedData.find(
            day => day.id === dayId
        );
        const eventIndexToRemove = dayObj.events.findIndex(
            event => event.details === eventDetails
        );
        dayObj.events.splice(eventIndexToRemove, 1);

    },

}